package com.mybatis.proxy;

import com.mybatis.cfg.Mapper;
import com.mybatis.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;

public class MapperProxy implements InvocationHandler {

    private Map<String, Mapper> mappers;

    private Connection connection;

    public MapperProxy(Map<String, Mapper> mappers, Connection connection) {
        this.mappers = mappers;
        this.connection = connection;
    }

    /**
     * 用于对方法进行增强，我们的增强其实就是调用jdbc的查询sql
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //获取方法名
        String methodName = method.getName();
        //获取方法所在类全限定类名
        String className = method.getDeclaringClass().getName();
        //组合key
        String key = className + "." + methodName;
        //获取mappers中的mapper对象
        Mapper mapper = mappers.get(key);
        //判断是否有对象
        if(null == mapper){
            throw new IllegalArgumentException("参数有误");
        }
        //查询sql语句
        return new Executor().selectList(mapper, connection);
    }
}
